import time
import pyautogui
import pygetwindow as gw

from my_package.ring_pk import end_img_path, cancel_btn_img_path
from my_package.screen_utils import return_default_screen
from my_package.xqol_utils import get_window_size, get_game_windows, find_btn_location_window

menu_btn_x = 25
menu_btn_y = 380

# 最左下角的确定按钮
left_end_confirm_btn_x = 22
left_end_confirm_btn_y = 446

# 最右下角的取消按钮
right_bottom_confirm_btn_x = 278
right_bottom_confirm_btn_y = 447

def buy_ticket_by_account_list(account_list, quantity=40, delay=0):
    """
    【根据账号】批量购买lv29英雄入场券
    :param account_list: 账号列表
    :param quantity: 购买数量
    :param delay: 额外的延迟秒
    :return:
    """
    if account_list is None or len(account_list) == 0:
        print("请传入需要购买入场券的账号")
        return False

    windows = get_game_windows(account_list)
    if len(windows) == 0:
        print("请先运行xqApp程序")
        return False

    res_dict = {}
    for window in windows:
        success = False
        while not success:
            res_dict = do_buy_ticket(window, quantity, delay)
            print(window.title, "购买结果", res_dict)
            # 从返回字典中获取当前窗口的购买状态
            success = res_dict.get(window.title, False)
            if not success:
                print(f"{window.title} 购买失败，重新尝试...")
            else:
                print(f"{window.title} 购买成功！进入下一个窗口")

    # 筛选出购买失败的窗口
    failed_list = [title for title, success in res_dict.items() if not success]

    print("购买失败的窗口列表:", failed_list)
    if (len(failed_list)) > 0:
        print("有账号购买失败，再次尝试购买一下")
        buy_ticket_by_account_list(failed_list, quantity, delay)
    return len(failed_list) == 0  # 如果没有失败的，返回 True


def buy_ticket_by_windows(windows=None, quantity=40):
    """
    【根据据窗口集合】批量购买lv29英雄入场券
    :param windows: 窗口集合。如果不传，则默认为所有窗口标题是xqApp开头的窗口，进行购买入场券
    :param quantity: 购买的数量
    :return:
    """
    if windows is None or len(windows) == 0:
        # 获取当前所有窗口
        windows = gw.getWindowsWithTitle("xqApp")
    print("准备购买购物券，当前所有xqApp窗口", windows)
    if len(windows) == 0:
        print("没有运行中的窗口")
        exit()
    for window in windows:
        do_buy_ticket(window, quantity)


def do_buy_ticket(window=None, quantity=40, delay=0):
    """
    【根据窗口】购买lv29英雄入场券
    :param window: 某个具体的窗口，不传则会操作运行的xqApp窗口，进行购买入场券
    :param quantity: 购买的数量，默认40张
    :param delay: 额外追加延迟秒，一般在电脑多开窗口很多的时候使用
    :return: dict，key 为 window.title，value 为是否成功购买的布尔值
    示例结果：
        {
            "xqApp hujun6": True,
            "xqApp hujun8": True,
            "xqApp xqolxz1": False
        }
    """
    print("本次将购买的数量", quantity)
    if window is None:
        # 获取当前所有窗口
        result = gw.getWindowsWithTitle("xqApp")
    else:
        result = [window]

    print("当前所有xqApp窗口", result)

    result_dict = {}  # 定义返回字典

    for window in result:
        # 先回到默认场景
        return_default_screen(window)
        # 初始化购买标识
        success_flag = False
        try:
            time.sleep(0.5)
            # 将窗口激活并置顶
            window.activate()
            time.sleep(0.5)
            pyautogui.click(window.left + 130, window.top + 10)
            time.sleep(delay)
        except Exception as e:
            print(f"{window.title} 窗口操作失败：{e}")
            time.sleep(0.5)
            try:
                window.activate()
            except:
                pass
            result_dict[window.title] = success_flag
            continue

        # 定义截图区域
        res = get_window_size(window._hWnd)
        width_main, height_main, window_x_main, window_y_main = res

        # 鼠标移动到[菜单],这里可以计算好位置,不用再去图片识别找位置
        pyautogui.moveTo(window_x_main + menu_btn_x, window_y_main + menu_btn_y)
        # # 点击菜单
        pyautogui.click()

        # 延迟一下,等待接口响应
        time.sleep(1 + delay)

        # 按下[6]
        pyautogui.write("6")
        time.sleep(1 + delay)
        # 按下[3]
        pyautogui.write("3")
        # 按下6或者方向右键,切换到[银票]标签页面
        time.sleep(2 + delay)
        pyautogui.press('right')
        time.sleep(2 + delay)
        # 会按下三次下箭头键，每次间隔 0.1 秒。
        pyautogui.press('down', presses=3, interval=0.2)
        print("鼠标已经到达[LV29 英雄擂入场券]")

        # 点击确认按钮
        pyautogui.moveTo(window_x_main + left_end_confirm_btn_x, window_y_main + left_end_confirm_btn_y)
        pyautogui.click()
        time.sleep(1 + delay)

        # 按5确认购买
        pyautogui.write("5")
        time.sleep(1 + delay)

        # 输入购买的数量
        if quantity > 10:
            # 动态输入数量
            pyautogui.write(str(quantity // 10))  # 十位
            time.sleep(1)
            pyautogui.write(str(quantity % 10))  # 个位
        else:
            pyautogui.write(str(quantity))

        # 移动到[确认]按钮
        pyautogui.moveTo(window_x_main + left_end_confirm_btn_x, window_y_main + left_end_confirm_btn_y)
        # 点击确认
        pyautogui.click()
        time.sleep(1 + delay)
        pyautogui.click()
        time.sleep(1 + delay)
        pyautogui.click()

        # # 移动到[取消]按钮
        pyautogui.moveTo(window_x_main + right_bottom_confirm_btn_x, window_y_main + right_bottom_confirm_btn_y)
        pyautogui.click()

        success_flag = True
        print(window.title, "购买完毕 从商城退出, 进入主界面")
        # 更新结果字典
        result_dict[window.title] = success_flag
    return result_dict

def click_window(window):
    pyautogui.click(window.left + 140, window.top + 10)


def buy_ticket_fast(windows=None, quantity=40, delay=1):
    # 获取当前所有窗口
    if windows is None or len(windows) == 0:
        # 获取当前所有窗口
        windows = gw.getWindowsWithTitle("xqApp")
    if len(windows) == 0:
        print("没有运行中的窗口")
        exit()
    # 1、依次点击菜单
    for window in windows:
        try:
            window.activate()
            click_window(window)
        except Exception as e:
            print(window.title, e)
        # 如果是比武結束場景，需要點擊一下取消按鈕
        time.sleep(0.1)
        res_end = find_btn_location_window(window, end_img_path)
        if len(res_end) > 0:
            res_cancel = find_btn_location_window(window, cancel_btn_img_path)
            if len(res_cancel) > 0:
                pyautogui.click(window.left + res_cancel[0] + 3, window.top + res_cancel[1] + 2)
        print(window.title, window.left, window.top)
        pyautogui.click(window.left + menu_btn_x, window.top + menu_btn_y)
    # 延迟一下
    time.sleep(3 + delay)
    print("等待主菜单界面打开")
    # 2、依次点击6
    for window in windows:
        window.activate()
        click_window(window)
        pyautogui.write("6")
    # 延迟一下
    time.sleep(3 + delay)
    print("按6打开商城界面")
    # 3、依次点击3
    for window in windows:
        window.activate()
        click_window(window)
        pyautogui.write("3")
    # 延迟一下
    time.sleep(3 + delay)
    # 4、方向右键,切换到[银票]标签页面
    for window in windows:
        window.activate()
        click_window(window)
        pyautogui.press('right')
    # 延迟一下
    time.sleep(3 + delay)
    # 5、前往购物券
    for window in windows:
        window.activate()
        click_window(window)
        time.sleep(0.5 + delay)
        # 会按下三次下箭头键，每次间隔 0.1 秒。
        pyautogui.press('down', presses=3, interval=0.2)
    # 延迟一下
    time.sleep(3 + delay)
    for window in windows:
        window.activate()
        click_window(window)
        # 点击确认按钮
        pyautogui.click(window.left + left_end_confirm_btn_x, window.top + left_end_confirm_btn_y)
    # 延迟一下
    time.sleep(3 + delay)
    # 按5确认购买
    for window in windows:
        window.activate()
        click_window(window)
        pyautogui.write("5")
    # 输入购买的数量
    for window in windows:
        window.activate()
        click_window(window)
        # 输入购买的数量
        if quantity > 10:
            # 动态输入数量
            pyautogui.write(str(quantity // 10))  # 十位
            time.sleep(1 + delay)
            pyautogui.write(str(quantity % 10))  # 个位
        else:
            pyautogui.write(str(quantity))
    # 延迟一下
    time.sleep(3 + delay)
    # 点击确认
    for window in windows:
        window.activate()
        click_window(window)
        pyautogui.click(window.left + left_end_confirm_btn_x, window.top + left_end_confirm_btn_y)
    # 再次确认
    time.sleep(3)
    for window in windows:
        window.activate()
        click_window(window)
        pyautogui.click(window.left + left_end_confirm_btn_x, window.top + left_end_confirm_btn_y)
    result_dict = {}  # 定义返回字典
    #
    time.sleep(3 + delay)
    # 点击取消按钮
    for window in windows:
        window.activate()
        click_window(window)
        pyautogui.click(window.left + right_bottom_confirm_btn_x, window.top + right_bottom_confirm_btn_y)
        # 更新结果字典
        result_dict[window.title] = True
        # 点击取消按钮
        pyautogui.click(window.left + right_bottom_confirm_btn_x, window.top + right_bottom_confirm_btn_y)
    return result_dict


if __name__ == '__main__':
    print("开始购买入场券")
    windows = get_game_windows(["hujun6", "hujun8", "hujun9", "hujun20", "hujun21", "hujun22"])
    buy_ticket_fast(windows=windows, quantity=40, delay=1)
    print("结束购买入场券")
